package my.chat.controller;

import com.alibaba.fastjson.JSONObject;
import my.chat.entity.ChatMsg;
import my.chat.service.ChatMsgService;
import my.chat.util.EmojiFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * ServerEndpoint注解是一个类层次的注解，它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 * ServerEndpoint可以把当前类变成websocket服务类
 */
@Controller
@ServerEndpoint(value = "/websocket/{userNo}")
public class ChatWebSocket {

    private static ChatMsgService chatMsgService;
    @Autowired
    public void setChatService(ChatMsgService chatService) {
        ChatWebSocket.chatMsgService = chatService;
    }

    private static int onlineCount = 0;
    private static final ConcurrentHashMap<String, ChatWebSocket> WEB_SOCKET_SET = new ConcurrentHashMap<>();
    private Session session;
    private String userNo = null;

    @OnOpen
    public void onOpen(@PathParam(value = "userNo") String userNo, Session session) {
        this.userNo = userNo;
        this.session = session;
        WEB_SOCKET_SET.put(userNo, this);
        addOnlineCount();
    }


    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (!StringUtils.isEmpty(userNo)) {
            WEB_SOCKET_SET.remove(userNo);
            subOnlineCount();
        }
    }


    /**
     * 收到客户端消息后调用的方法
     */
	@OnMessage
    public void onMessage(String chatmsg, Session session) {
        JSONObject jsonObject = JSONObject.parseObject(chatmsg);
        //给指定的人发消息
        sendToUser(jsonObject.toJavaObject(ChatMsg.class));
    }


    /**
     * 给指定的人发送消息
     * @param chatMsg 消息对象
     */
    public void sendToUser(ChatMsg chatMsg) {
        String reviceUserid = chatMsg.getAcceptUserId();
        String sendMessage = chatMsg.getMsg();
        sendMessage= EmojiFilter.filterEmoji(sendMessage);
        chatMsgService.insertChatMsg(new ChatMsg().setId(UUID.randomUUID().toString().replace("-", ""))
                .setSignFlag(chatMsg.getSignFlag())
                .setAcceptUserId(reviceUserid).setSendUserId(userNo).setMsg(sendMessage));
        try {
            if (WEB_SOCKET_SET.get(reviceUserid) != null) {
                WEB_SOCKET_SET.get(reviceUserid).sendMessage(userNo+"|"+sendMessage);
            }else{
                WEB_SOCKET_SET.get(userNo).sendMessage("0"+"|"+"当前用户不在线");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 给所有人发消息
     */
    private void sendAll(String message) {
        String sendMessage = message.split("[|]")[1];
        //遍历HashMap
        for (String key : WEB_SOCKET_SET.keySet()) {
            try {
                //判断接收用户是否是当前发消息的用户
                if (!userNo.equals(key)) {
                    WEB_SOCKET_SET.get(key).sendMessage(sendMessage);
                    System.out.println("key = " + key);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }


    /**
     * 这个方法与上面几个方法不一样。没有用注解，是根据自己需要添加的方法。
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        ChatWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        ChatWebSocket.onlineCount--;
    }
}

